<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-date-picker
            v-model="dataRange"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="daterange"
            startPlaceholder="开始日期"
            endPlaceholder="结束日期"
            style="flex-grow: 0; width: 350px"
            clearable
            @change="getAxiosData(true)"
          ></base-date-picker>
          <base-input-search
            v-model="filterData.dramaTitle"
            clearable
            placeholder="请输入短剧名称"
            style="width: 230px"
            maxlength="30"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.referralLinkName"
            clearable
            maxlength="20"
            placeholder="请输入投放链接名称"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.referralLinkId"
            clearable
            maxlength="20"
            placeholder="请输入投放链接ID"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.userId"
            clearable
            maxlength="20"
            placeholder="请输入用户ID"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.openId"
            clearable
            maxlength="20"
            placeholder="请输入openId"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
        </div>
      </div>
    </template>
    <el-table ref="elTableRef" v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
      <template #empty>
        <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>
      <el-table-column
        fixed
        type="index"
        :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
        label="编号"
        sortable
        width="60"
        align="center"
        headerAlign="center"
      ></el-table-column>
      <el-table-column fixed label="头像" prop="dramaTitle" minWidth="68">
        <template #default="{ row }">
          <base-image style="width: 40px; height: 40px; border-radius: 60%" :src="row.avatar || avatarUrl"></base-image>
        </template>
      </el-table-column>
      <el-table-column fixed label="昵称" prop="nickname" minWidth="180">
        <template #default="{ row }">
          <div class="content-wrap">
            <p>
              ID:
              <span class="highlighted" @click="clipboard(row.userId)">{{ row.userId }}</span>
            </p>
            <p>
              <span>{{ row.nickname || '-' }}</span>
            </p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="sex" minWidth="80">
        <template #default="{ row }">
          <el-tag v-if="row.sex === 1" key="el-tag-1" effect="plain" size="small">男</el-tag>
          <el-tag v-else-if="row.sex === 2" key="el-tag-2" type="danger" effect="plain" size="small">女</el-tag>
          <el-tag v-else key="el-tag-3" type="warning" effect="plain" size="small">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" prop="createTime" minWidth="120">
        <template #default="{ row }">
          <div>
            <p>{{ row.createTime?.split(' ')?.[0] }}</p>
            <p>{{ row.createTime?.split(' ')?.[1] }}</p>
          </div>
        </template>
      </el-table-column>
      <!--      <el-table-column label="会员到期日" prop="vipExpireTime" minWidth="120"> -->
      <!--        <template #default="{ row }"> -->
      <!--          <div> -->
      <!--            <p>{{ row.vipExpireTime?.split(' ')?.[0] }}</p> -->
      <!--            <p>{{ row.vipExpireTime?.split(' ')?.[1] }}</p> -->
      <!--          </div> -->
      <!--        </template> -->
      <!--      </el-table-column> -->
      <el-table-column label="K币余额" prop="virtualCoins" minWidth="90"></el-table-column>
      <el-table-column label="充值总金额" prop="payAmount" minWidth="100"></el-table-column>
      <el-table-column label="最近充值金额" prop="lastUserPayMoney" minWidth="120"></el-table-column>
      <el-table-column label="最近充值时间" prop="lastUserPayActionTime" minWidth="120">
        <template #default="{ row }">
          <div>
            <p>{{ row.lastUserPayActionTime?.split(' ')?.[0] }}</p>
            <p>{{ row.lastUserPayActionTime?.split(' ')?.[1] }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="充值链接" minWidth="220">
        <template #default="{ row }">
          <div class="content-wrap">
            <p>
              ID:
              <span class="highlighted" @click="clipboard(row.referralLinkId)">{{ row.referralLinkId }}</span>
            </p>
            <p>
              <span>{{ row.referralLinkName || '-' }}</span>
            </p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="最近观看记录" prop="lastSeeDramaTitle" minWidth="160">
        <template #default="{ row }">
          <div>
            <p class="ellipsis">{{ row.lastSeeDramaTitle }}</p>
            <p>{{ row.lastSeeDramaSeq ? `第${row.lastSeeDramaSeq}集` : '' }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="最近观看时间" prop="lastSeeTime" minWidth="120">
        <template #default="{ row }">
          <p>{{ row.lastSeeTime?.split(' ')?.[0] }}</p>
          <p>{{ row.lastSeeTime?.split(' ')?.[1] }}</p>
        </template>
      </el-table-column>
      <!--      <el-table-column label="登录账号" prop="username" minWidth="180"></el-table-column> -->
      <!--      <el-table-column label="会员" prop="isVip" minWidth="80"> -->
      <!--        <template #default="{ row }"> -->
      <!--          <el-tag v-if="row.isVip === 1" key="el-tag-1" type="success" size="small">会员</el-tag> -->
      <!--          <el-tag v-else-if="row.isVip === 0" key="el-tag-2" type="primary" size="small">非会员</el-tag> -->
      <!--          <el-tag v-else key="el-tag-3" type="warning" size="small">未知</el-tag> -->
      <!--        </template> -->
      <!--      </el-table-column> -->
      <!--      <el-table-column label="收藏数量" prop="collectDramaNum" minWidth="90"></el-table-column> -->
      <!--      <el-table-column label="最近充值行为" prop="lastUserPayAction" minWidth="140"></el-table-column> -->
      <!--      <el-table-column label="联系电话" prop="phone" minWidth="120"></el-table-column> -->
      <!--      <el-table-column label="生日" prop="birthday" minWidth="120"></el-table-column> -->
      <!--      <el-table-column fixed="right" label="状态" width="90" align="center" headerAlign="center"> -->
      <!--        <template #default="{ row }"> -->
      <!--          <el-switch -->
      <!--            v-model="row.status" -->
      <!--            :disabled="row.admin" -->
      <!--            style="&#45;&#45;el-switch-on-color: var(&#45;&#45;el-color-success); &#45;&#45;el-switch-off-color: var(&#45;&#45;el-color-danger)" -->
      <!--            inlinePrompt -->
      <!--            activeText="正常" -->
      <!--            inactiveText="已封禁" -->
      <!--            :activeValue="0" -->
      <!--            :inactiveValue="1" -->
      <!--            :loading="row._statusLoading" -->
      <!--            :beforeChange="() => handleSetStateSingle(row)" -->
      <!--          ></el-switch> -->
      <!--        </template> -->
      <!--      </el-table-column> -->
      <el-table-column label="会员到期时间" prop="vipExpireTime" minWidth="120"></el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import { type AppUser, type AppUserListRequest, getAppUserListAxios } from '@/api/app-user-management';
  import avatarUrl from '@/assets/images/account/avatar.svg';
  const { proxy } = getCurrentInstance() as any;
  import { useClipboard } from '@vueuse/core';

  const { copy, isSupported } = useClipboard({ legacy: true });

  type _AppUser = AppUser & {
    /** 修改冻结状态的加载状态 */
    _statusLoading?: boolean;
  };
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });

  const dataRange = ref<[string, string] | undefined>();
  const filterData: Ref<AppUserListRequest> = ref<AppUserListRequest>({
    referralLinkName: '',
    dramaTitle: '',
    referralLinkId: '',
    userId: '',
    isVip: undefined,
    sex: undefined,
    openId: '',
    phone: '',
    startDate: '',
    endDate: '',
    current: 1,
    size: 40,
  });

  const tableData: Ref<_AppUser[]> = ref([]);
  const description = ref('');
  onMounted(() => {
    dataRange.value = [proxy.$dayjs().format('YYYY-MM-DD'), proxy.$dayjs().format('YYYY-MM-DD')];
    getAxiosData();
  });

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    if (Array.isArray(dataRange.value) && dataRange.value.length) {
      filterData.value.startDate = `${dataRange.value[0]} 00:00:00`;
      filterData.value.endDate = `${dataRange.value[1]} 23:59:59`;
    } else {
      filterData.value.startDate = '';
      filterData.value.endDate = '';
    }
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getAppUserListAxios(filterData.value);
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  /** 修改单个解冻状态 */
  // async function handleSetStateSingle(row: _AppUser): Promise<boolean> {
  //   const name = row.status === 0 ? '封禁' : '解封';
  //   try {
  //     row._statusLoading = true;
  //     await changeStatusAppUserAxios(row.userId);
  //     row._statusLoading = false;
  //     ElToast.success(`${name}成功`);
  //     return Promise.resolve(true);
  //   } catch (error) {
  //     row._statusLoading = false;
  //
  //     ElToast.error(error.msg || `${name}失败，-BD004`);
  //     return Promise.reject(false);
  //   }
  // }

  /** 复制 */
  async function clipboard(text: string) {
    if (!isSupported) {
      ElToast.error('您的浏览器不支持复制');
    } else {
      try {
        await copy(text);
        ElToast.success('复制成功');
      } catch (error) {
        ElToast.error('复制失败');
      }
    }
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      // display: grid;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }

  .content-wrap {
    white-space: wrap;
  }
</style>
